/**
 * Created by Scoot on 2017/6/29.
 */

var payTpye = "1";
var designType = '';
var addressId = '';
var invoiceId = localStorage.getItem("invoice_id")||"";//发票id
var cartIds = localStorage.getItem("customize_cartIds")||"";
var code = localStorage.getItem("customize_orderCode")||"";
var isMore = code.indexOf(",");
var sendCode = isMore>-1?code.split(",")[0]:code; //多个订单号中的第一个订单号
var isWX = false;

var isApp = false;
var equipmentType = "common";

var dataLength = 1;

if (/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)) {
    equipmentType= "ios";
} else if (/(Android)/i.test(navigator.userAgent)) {
    equipmentType = "android";
} else {
    equipmentType = "common";
}

$(function(){

    isWeiXin();

    getConfirmPayForDetail();


    if(isWX){
        post({ //判断当前订单的微信支付状态
            url:"/customizeOrder/queryWechatStatus",
            data: {code:sendCode},
            success:function(data){
                if(data=="success"){
                    weiXinPay();
                }else{
                    queryOrderStatus();
                }
            }
        })
    }else{
        queryOrderStatus();//获取订单状态
    }

    post({
        url : "/isLogin",
        success : function(data){
            if(!data){
                go("/login/index.html");
            }
        }
    });

    //点击确认去支付
    $(".now-buy .normal-buy").click(function(){
        if(addressId == ""){
            $(".no_adrees").removeClass("tab");
        }else{
            post({
                url:"/customizeOrder/findStatus",
                data:{code:code},
                success:function(data){
                    if (data == "success") {
                        goPay();
                    } else {
                        $(".gat_background .gat_alert p").text("对不起，无法购买，存在此订单，请在订单列表中查看订单详细信息!");
                        $(".gat_background").removeClass("tab");
                        $(".gat_alert_affirm").click(function () {
                            go("/customize/orderlist/index.html");
                        });
                    }
                }
            })
        }

    });

    //选择支付方式
    $(".pay_list").click(function(){
        payTpye = $(this).data("type");
        $(".pay_list").removeClass("pay-selected");
        $(this).addClass("pay-selected");
    });

    $(".message_alert_affirm").click(function(){
        $(".message_alert").addClass("tab");
    });

    $(".adrees_cancel").click(function(){
        $(".no_adrees").addClass("tab");
    });

    $(".adrees_affirm").click(function(){
        go("/member/addressmanagement/selectaddress.html?type=newCustomize");
    });

    $(".gat_alert_affirm").click(function(){
        go("/customize/orderlist/index.html");
    });

    $(".head-back-2").click(function(){
        var _url = localStorage.getItem("customize_order_return");
        if(_url){
            go(_url);
        }else{
            go("/customize/cart/index.html");
        }
    });


});

//支付
function goPay(){

    if(equipmentType == "ios"){
        try{
            //ifApp();
            window.webkit.messageHandlers.ifApp.postMessage('');//ios换内核后用此方法调微信客户端支付
            isApp = true;
        }catch (e){
            isApp = false;
        }
    }else if(equipmentType == "android"){
        try{
            isApp = contact.ifApp();
        }catch (e){
            isApp = false;
        }
    }else{
        isApp = false;
    }

    if(isWX && payTpye == "1"){  //微信支付
        window.open(SERVER_CONTEXT_PATH+"/customizeOrder/saveWeChat?code="+code+"&cartIds="+cartIds+"&addressId="+addressId+"&invoiceId="+invoiceId ,"_self");
    }else{
        if(isApp == true && payTpye == '1'){//如果是在app并且是微信支付
            appPay();
        }else if(isApp == false && payTpye == '1'){
            $(".message_alert").removeClass("tab");
        }else{ //支付宝支付
            alipay();
        }
    }

}

function appPay(){

    var _data={code:code,cartIds:cartIds,addressId:addressId,invoiceId:invoiceId};

    post({
        url:'/customizeOrder/saveWeChatAPP',
        data:_data,
        success:function(data){
            var p = data.split(',');
            if(equipmentType == "ios"){
                var message = {
                    'partnerid' : p[0],
                    'prepayid' : p[1],
                    'packages' : p[2],
                    'noncestr' : p[3],
                    'timestamp' : p[4],
                    'sign' : p[5]
                };
                window.webkit.messageHandlers.wxpay.postMessage(message);
                //wxpay(p[0],p[1],p[2],p[3],p[4],p[5]);
            }else{
                contact.wxpay(p[0],p[1],p[2],p[3],p[4],p[5]);
            }
        }
    })
}

function alipay(){

    var _data={code:code,cartIds:cartIds,addressId:addressId,invoiceId:invoiceId};

    post({
        url:"/customizeOrder/saveOrderAlipay",
        data:_data,
        success:function(data){
            if(isWX){
                var _url = encodeURIComponent("/alipay/customizeConfirmPayFor?code=" + sendCode );
                go("/mobileorder/pay_tip.html?url="+_url);
                //go("/mobileorder/pay_tip.html?code="+sendCode + "&url=customizeConfirmPayFor");
            }else{
                go('/alipay/customizeConfirmPayFor?code='+sendCode );
            }
        },
        error:function(msg){
            //alert(msg);
            $(".gat_background .gat_alert p").text(msg);
            $(".gat_background").removeClass("tab");
        }
    });

}

function weiXinPay() {

    var _appId = '';
    var _timeStamp = '';
    var _nonceStr = '';
    var _paySign = '';
    var _signType = '';
    var prepay_id = '';

    post({
        url: "/weChat/getWeChatDto",
        data: {orderCode: sendCode},
        success: function (data) {
            _appId = data.appId;
            _timeStamp = data.timeStamp;
            _nonceStr = data.nonceStr;
            _paySign = data.paySign;
            _signType = data.signType;
            prepay_id = data.prepay_id;
            if (typeof WeixinJSBridge == "undefined") {
                if (document.addEventListener) {
                    document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
                } else if (document.attachEvent) {
                    document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
                    document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
                }
            } else {
                onBridgeReady();
            }
        },
        error: function (msg) {
            alert(msg)
        }
    });

    function onBridgeReady(){
        WeixinJSBridge.invoke(
            'getBrandWCPayRequest', {
                "appId":_appId,     //公众号名称，由商户传入
                "timeStamp":_timeStamp,         //时间戳，自1970年以来的秒数
                "nonceStr":_nonceStr, //随机串
                "package":prepay_id,
                "signType":_signType,         //微信签名方式：
                "paySign":_paySign //微信签名
            },
            function(res){
                if(res.err_msg == "get_brand_wcpay_request:ok" ) {
                    go("/payresult/success.html");

                }else{
                    go("/payresult/fail.html");
                }     // 使用以上方式判断前端返回,微信团队郑重提示：res.err_msg将在用户支付成功后返回    ok，但并不保证它绝对可靠。
            }
        );
    }

}

//获取订单状态
function queryOrderStatus(){
    post({
        url:"/customizeOrder/findStatus",
        data:{code:code},
        success:function(data){
            if (data == "success") {
                $(".now-buy .normal-buy").removeAttr("disabled");
            } else {
                $(".gat_background .gat_alert p").text("对不起，无法购买，存在此订单，请在订单列表中查看订单详细信息!");
                $(".gat_background").removeClass("tab");
                $(".gat_alert_affirm").click(function () {
                    go("/customize/orderlist/index.html");
                });
            }
        }
    })
}

//读取订单信息内容
function getConfirmPayForDetail(){

    if(invoiceId != ""){
        post({
            url:"/invoice/load/"+invoiceId,
            success:function(data){
                //console.log(data);
                $(".invoice .invoice-type").text(data.invoiceContent);
                $(".invoice .invoice-name").text(data.invoiceCategory.text+"："+data.title);
            },
            error:function(msg){
                console.log(msg)
            }
        });
    }else{
        $(".invoice .invoice-type").text("不需要发票");
        $(".invoice .invoice-name").addClass("tab");
    }
    $(".invoice>p:first-child").click(function(){
        go("/customize/invoice/index.html");
    });

    post({
        url:"/customizeCart/confirmPayFordetail",
        data:{cartIds:cartIds},
        success:function(data){
            console.log(data);
            dealDetail(data );
        },
        error:function(msg){
            console.log(msg)
        }
    })
}

//处理订单内容
function dealDetail(info){

    if(info.memberAddressDTO){
        addressId = info.memberAddressDTO.id;
        var _detail = '<p class="name clear">';
        _detail += '<span class="left">收货人：<b>'+info.memberAddressDTO.consignee+'</b></span>';
        _detail += '<i class="right">'+info.memberAddressDTO.mobile+'</i></p>';
        _detail += '<p class="more_single">收货地址：<i>'+info.memberAddressDTO.addressDetail+'</i></p>';
        $(".normal-address .detail").html(_detail);
        $(".no-address").addClass("tab");
        $(".normal-address").removeClass("tab");
    }

    var productList = info.productList;
    var totalPrice = 0;
    var _html = '';
    dataLength = productList.length;
    for(var i=0;i<productList.length;i++){
        //商品信息
        _html += '<div><div class="goods-producter"><div class="goods clear">';
        _html += '<img src="'+SERVER_CONTEXT_PATH+'/load/picture/'+productList[i]["productUrl"]+'" />';
        _html += '<div class="customize-type">'+(productList[i]["designType"]["name"] == "DESIGN" ? "定制" : "原厂")+'</div>';
        _html += '<ul class="left"><li class="single">定制商品：<span>'+productList[i]["productName"]+'</span></li>';
        var manufacturerSpecification = productList[i]["manufacturerSpecification"].split("  ");
        for(var k=0;k<manufacturerSpecification.length;k++){
            _html += '<li class="single">'+manufacturerSpecification[k]+'</span></li>';
        }
        _html += '</ul></div>';
        _html += '</div>';
        if(productList[i]["designType"]["name"] == "DESIGN"){
            //包装类别
            _html += '<div class="pack-kind"><div class="pack clear">';
            _html += '<img src="'+SERVER_CONTEXT_PATH+'/load/picture/'+productList[i]["packImageUrl"]+'" />';
            _html += '<ul class="left">';
            _html += '<li class="single">包装类别：<span>'+productList[i]["packName"]+'</span></li>';
            _html += '<li class="single">'+productList[i]["designerSpecification"]+'</span></li>';
            _html += '<li class="clear single">';
            for(var j=0;j<productList[i]["cartDesignerList"].length;j++){
                if(productList[i]["cartDesignerList"][j]["imageUrl"]){
                    _html += '<img src="'+SERVER_CONTEXT_PATH+'/load/picture/'+productList[i]["cartDesignerList"][j]["imageUrl"]+'" alt=""/>';
                }
            }
            _html += '</li></ul></div>';
            //设计商
            _html += '<div class="designer clear">';
            _html += '<p class="left single">设计商：<span>'+productList[i]["designer"]["name"]+'</span></p>';
            _html += '<img src="'+SERVER_CONTEXT_PATH+'/load/picture/'+productList[i]["designer"]["imageUrl"]+'" alt=""></div></div>';
        }

        //费用
        _html += '<div class="money"><ul><li class="clear">';
        _html += '<span class="left">商品金额：</span><i class="left">'+returnFloat(productList[i]["price"]) +' x '+productList[i]["num"]+'箱</i>';
        var amount = productList[i]["price"]*productList[i]["num"];
        var makeFee = productList[i]["makeFee"]*productList[i]["num"];
        var subtotal = amount+makeFee+productList[i]["designFee"];
        totalPrice += subtotal;
        _html += '<b class="right">￥'+returnFloat(amount)+'</b></li>';
        if(productList[i]["designType"]["name"] == "DESIGN"){
            _html += '<li class="clear"><span class="left">设计费：</span><b class="right">￥'+returnFloat(productList[i]["designFee"])+'</b></li>';
            _html += '<li class="clear"><span class="left">制作费：</span><i class="left">'+returnFloat(productList[i]["makeFee"])+' x '+productList[i]["num"]+'箱</i>';
            _html += '<b class="right">￥'+returnFloat(makeFee)+'</b></li>';
        }
        _html += '<li class="clear"><span class="left">运费：</span><b class="right">￥0.00</b></li>';
        _html += '</ul><p>注：定制商品不支持七天无理由退货<span class="right subtotal"><i>小计：</i>￥'+returnFloat(subtotal)+'</span></p></div>';
        _html += '';
        _html += '</div>';
    }
    $(".container .main").html(_html);
    $(".now-buy .total").text("￥"+returnFloat(totalPrice));

    if(equipmentType == "ios"&& isWX == false){
        try{
            window.webkit.messageHandlers.ifApp.postMessage('');//ios换内核后用此方法调微信客户端支付
            isApp = true;
            if(dataLength == 1){
                $(".now-buy").css({"position":"static"});
                $(".container").css({"paddingBottom":"0.2rem"});
            }
        }catch (e){
            isApp = false;
        }
    }

}


//判断是否是微信
function isWeiXin(){
    var ua = window.navigator.userAgent.toLowerCase();
    if(ua.match(/MicroMessenger/i) == 'micromessenger'){
        isWX = true;
        return true;
    }else{
        isWX = false;
        return false;
    }
}

function iosApp(str){
    isApp = true;
    return true;
}

